package com.hisan.freeride.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.bumptech.glide.Glide;
import com.hisan.freeride.R;
import com.hisan.freeride.common.Dialog.DialogLogok;
import com.hisan.freeride.common.Dialog.DialogLogout;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.callback.NoDialogCallback;
import com.hisan.freeride.common.event.DataSynEvent;
import com.hisan.freeride.common.listener.IEditTextChangeListener;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.CompressPhotoUtils;
import com.hisan.freeride.common.utils.GlideImageLoader;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.WorksSizeCheckUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.databinding.RealnameBinding;
import com.hisan.freeride.home.model.ImageUrl;
import com.hisan.freeride.home.model.MyImageUrl;
import com.hisan.freeride.home.model.Realname;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.callback.ConfigButton;
import com.mylhyl.circledialog.callback.ConfigDialog;
import com.mylhyl.circledialog.params.ButtonParams;
import com.mylhyl.circledialog.params.DialogParams;
import com.ziyeyouhu.library.KeyboardTouchListener;
import com.ziyeyouhu.library.KeyboardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



/**
 * 创建时间 : 2017/6/12
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：实名认证页面
 */
public class RealNameActivity extends BaseActivity<RealnameBinding> {
    //身份证默认图片集合
    private ArrayList<ImageItem> imageItems1;
    //身份证正面图片集合
    private ArrayList<ImageItem> imageItems2;
    //身份证正面、手持身份证照片
    private String avatar, avatar2 ;
    private  Intent intent;
    private String name;
    private String identity;
    private KeyboardUtil keyboardUtil;
    //用户识别照片顺序
    private int type=0;


    @Override
    protected int getLayoutId() {
        return R.layout.realname;
    }

    @Override
    protected void initView() {
        imageItems1=new ArrayList<>();
        imageItems2=new ArrayList<>();
        EventBus.getDefault().register(this);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(1);    //最多选择1张
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        keyboardUtil = new KeyboardUtil(this, mBinding.rootView, mBinding.svMain);;
        keyboardUtil.setKeyBoardStateChangeListener(new KeyBoardStateListener());
        keyboardUtil.setInputOverListener(new inputOverListener());
        mBinding.identity.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_X , -1));
        keyboardUtil.setOtherEdittext(mBinding.name);
        mBinding.welfare.setEnabled(false);
        //1.创建工具类对象 把要改变颜色的Button先传过去
        WorksSizeCheckUtil.textChangeListener textChangeListener = new WorksSizeCheckUtil.textChangeListener(mBinding.welfare);
        //2.把所有要监听的edittext都添加进去
        textChangeListener.addAllEditText(mBinding.name,mBinding.identity);
        //3.接口回调 在这里拿到boolean变量 根据isHasContent的值决定 tv 应该设置什么颜色
        WorksSizeCheckUtil.setChangeListener(new IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                if(isHasContent){
                    mBinding.welfare.setEnabled(true);
                }else{
                    mBinding.welfare.setEnabled(false);
                }
            }
            @Override
            public void afterChange(Editable editable) {}
        });
    }

    @Override
    protected void initEvent() {
        mBinding.identitySelect.setOnClickListener(v -> {
            keyboardUtil.hideKeyboardLayout();
            if (!CollectionUtils.isNullOrEmpty(avatar)){
                type=0;
                getmDialog("是否替换当前身份证照片？","取消","确定").show();
            }else{
                toImage(0);
            }
        });
        mBinding.identitySelect2.setOnClickListener(v -> {
            keyboardUtil.hideKeyboardLayout();
            if (!CollectionUtils.isNullOrEmpty(avatar2)){
                type=1;
                getmDialog("是否替换当前身份证照片？","取消","确定").show();
            }else{
                toImage(1);
            }
        });
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.welfare.setOnClickListener(v -> {
            name=mBinding.name.getText().toString();
            identity=mBinding.identity.getText().toString();
            if (CollectionUtils.isNullOrEmpty(name)||CollectionUtils.isNullOrEmpty(identity)
                    ||CollectionUtils.isNullOrEmpty(avatar)||CollectionUtils.isNullOrEmpty(avatar2)){
                showToast("请输入完整信息.....");
                return;
            }else{
                DialogLogout.getInstance().show(getSupportFragmentManager(), "DialogLogout");
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<Realname>get(AppConfig.Getrealname)
                .tag(this)
                .execute(new DialogCallback<Realname>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Realname> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)) {
                                if (isNull(response)){
                                    mBinding.name.setText(response.body().getRealname());
                                    mBinding.identity.setText(response.body().getId_card());
                                    mBinding.identity.setText(response.body().getId_card());
                                    avatar = response.body().getId_photo();
                                    if (!CollectionUtils.isNullOrEmpty(avatar)) {
                                        Glide.with(RealNameActivity.this)
                                                .load(avatar)
                                                .placeholder(R.mipmap.realname)//设置占位图
                                                .error(R.mipmap.realname)
                                                .into(mBinding.identityIamgeBig);
                                        mBinding.identityIamge.setVisibility(View.GONE);
                                        mBinding.identityText.setVisibility(View.GONE);
                                        mBinding.identityIamgeBig.setVisibility(View.VISIBLE);
                                    }
                                    avatar2 =response.body().getHand_photo();
                                    if (!CollectionUtils.isNullOrEmpty(avatar2)) {
                                        Glide.with(RealNameActivity.this)
                                                .load(avatar2)
                                                .placeholder(R.mipmap.realname)//设置占位图
                                                .error(R.mipmap.realname)
                                                .into(mBinding.identityIamgeBig2);
                                        mBinding.identityIamge2.setVisibility(View.GONE);
                                        mBinding.identityText2.setVisibility(View.GONE);
                                        mBinding.identityIamgeBig2.setVisibility(View.VISIBLE);
                                    }
                                    String  msg="";
                                    if (response.body().getReview()==0){
                                        msg="审核中";
                                        showToast(msg);
                                    }else if (response.body().getReview()==2) {
                                        msg = "审核被拒绝";
                                        showToast(msg);
                                    }
                                }

                            }else{
                                showErrorView(response.code());
                            }
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Realname> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }



    private void toImage(final int type) {
        //0：上传身份证正面照 1：上传手持身份证
        final String[] items = {"相册", "相机"};
        new CircleDialog.Builder(this)
                .configDialog(new ConfigDialog() {
                    @Override
                    public void onConfig(DialogParams params) {
                    }
                })
                .setTitle("选择照片")
                .setTitleColor(getResources().getColor(R.color.home_titel))
                .setItems(items, (parent, view, position, id) -> {
                    if (!CollectionUtils.isNullOrEmpty(items)){
                        if (items[position].equals("相册")){
                            Intent intent1 = new Intent(RealNameActivity.this,ImageGridActivity.class);
                            if (type==0){
                                startActivityForResult(intent1, 100);
                            }else{
                                startActivityForResult(intent1, 99);
                            }
                        }else{
                            Intent intent1 = new Intent(RealNameActivity.this,ImageGridActivity.class);
                            intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); //
                            if (type==0){
                                startActivityForResult(intent1, 100);
                            }else{
                                startActivityForResult(intent1, 99);
                            }
                        }
                    }
                })
                .setNegative("取消", null)
                .configNegative(new ConfigButton() {
                    @Override
                    public void onConfig(ButtonParams params) {
                        //取消按钮字体颜色
                        params.textColor = getResources().getColor(R.color.home_titel);
                    }
                })
                .show();
    }



    @Override
    public void onOk() {
        super.onOk();
        toImage(type);
    }

    @Override
    public void onCancel() {
        super.onCancel();
        if (mDialog.isShowing())mDialog.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(DataSynEvent event) {
        if (event.getid()==0){
            Saverealname(name,identity,avatar,avatar2);
        }else {
            finishActivity(true);
            showToast("实名认证成功,请等待后台审核");
        }
    }

    //创建实名认证
    private void Saverealname(String name, String identity, String avatar, String avatar2){
        OkGo.put(AppConfig.SaveRealname)
                .tag(this)
                .params("realname",name)
                .params("id_card",identity)
                .params("id_photo",avatar)
                .params("hand_photo",avatar2)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)){
                            if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                            setResult(99,intent);
                            DialogLogok.getInstance().show(getSupportFragmentManager(), "DialogLogok");
                        }else {
                            showError(response);
                        }

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                imageItems1 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems1 != null && imageItems1.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems1.size(); i++) {
                        if (i == imageItems1.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems1.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems1.get(i).path).append("\n");
                    }
                    formUpload();
                } else {
                    showToast("没有选择图片");
                }
            }else{
                imageItems2 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems2 != null && imageItems2.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems2.size(); i++) {
                        if (i == imageItems2.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems2.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems2.get(i).path).append("\n");
                    }
                    formUpload2();
                } else {
                    showToast("没有选择图片");
                }
            }
        }
    }

    //上传图片
    private  void formUpload(){
        ArrayList<File> files = new ArrayList<>();
        if (!CollectionUtils.isNullOrEmpty(imageItems1)) {
            new CompressPhotoUtils().CompressPhoto(RealNameActivity.this, imageItems1, new CompressPhotoUtils.CompressCallBack() {
                @Override
                public void success(List<String> list) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            files.add(new File(list.get(i)));
                        }
                        OkGo.post(AppConfig.UpLoad)
                                .tag(this)
                                .addFileParams("image", files)
                                .execute(new NoDialogCallback<Object>(RealNameActivity.this) {
                                    @Override
                                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                                        super.onSuccess(response);
                                        if (!CollectionUtils.isNullOrEmpty(response)) {
                                            if (isOk(response)) {
                                                try {
                                                   String data= GsonUtils.GsonString(response.body());
                                                    MyImageUrl json = GsonUtils.GsonToBean(data,MyImageUrl.class);
                                                    avatar = json.getFile();
                                                    if (!CollectionUtils.isNullOrEmpty(avatar)) {
                                                        Glide.with(RealNameActivity.this)
                                                                .load(avatar)
                                                                .placeholder(R.mipmap.realname)//设置占位图
                                                                .error(R.mipmap.realname)
                                                                .into(mBinding.identityIamgeBig);
                                                        mBinding.identityIamge.setVisibility(View.GONE);
                                                        mBinding.identityText.setVisibility(View.GONE);
                                                        mBinding.identityIamgeBig.setVisibility(View.VISIBLE);
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        } else {
                                            showError(response);
                                        }
                                    }

                                    @Override
                                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                                        super.onError(response);
                                        showError(response);
                                    }
                                });
                    }

                }
            });
        }
    }

    //上传图片
    private  void formUpload2(){
        ArrayList<File> files = new ArrayList<>();
        if (!CollectionUtils.isNullOrEmpty(imageItems2)) {
            new CompressPhotoUtils().CompressPhoto(RealNameActivity.this, imageItems2, new CompressPhotoUtils.CompressCallBack() {
                @Override
                public void success(List<String> list) {
                    if (list.size()>0){
                        for (int i = 0; i < list.size(); i++) {
                            files.add(new File(list.get(i)));
                        }
                        OkGo.post(AppConfig.UpLoad)
                                .tag(this)
                                .addFileParams("image", files)
                                .execute(new NoDialogCallback<Object>(RealNameActivity.this){
                                    @Override
                                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                                        super.onSuccess(response);
                                        if (!CollectionUtils.isNullOrEmpty(response)) {
                                            if (isOk(response)){
                                                try {
                                                    String data= GsonUtils.GsonString(response.body());
                                                    MyImageUrl json = GsonUtils.GsonToBean(data,MyImageUrl.class);
                                                    avatar2 = json.getFile();
                                                    if (!CollectionUtils.isNullOrEmpty(avatar2)) {
                                                        Glide.with(RealNameActivity.this)
                                                                .load(avatar2)
                                                                .placeholder(R.mipmap.realname)//设置占位图
                                                                .error(R.mipmap.realname)
                                                                .into(mBinding.identityIamgeBig2);
                                                        mBinding.identityIamge2.setVisibility(View.GONE);
                                                        mBinding.identityText2.setVisibility(View.GONE);
                                                        mBinding.identityIamgeBig2.setVisibility(View.VISIBLE);
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }else {
                                            showError(response);
                                        }
                                    }

                                    @Override
                                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                                        super.onError(response);
                                        showError(response);
                                    }
                                });
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    //自定义键盘监听物理返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) {
            if(keyboardUtil.isShow){
                keyboardUtil.hideSystemKeyBoard();
                keyboardUtil.hideAllKeyBoard();
                keyboardUtil.hideKeyboardLayout();
            }else {
                return super.onKeyDown(keyCode, event);
            }

            return false;
        } else
            return super.onKeyDown(keyCode, event);
    }
    class KeyBoardStateListener implements KeyboardUtil.KeyBoardStateChangeListener {

        @Override
        public void KeyBoardStateChange(int state, EditText editText) {}}

    class inputOverListener implements KeyboardUtil.InputFinishListener {

        @Override
        public void inputHasOver(int onclickType, EditText editText) {}}
}
